import { fromError } from 'zod-validation-error'
import { createRoleSchema, rolesTable } from '~~/server/db/schema/role'
import { db } from '~~/server/db'
import type { QueryError } from 'mysql2'

export default defineEventHandler(async (event) => {
  const validationResult = await readValidatedBody(event, (body) =>
    createRoleSchema.safeParse(body)
  )

  if (!validationResult.success) {
    throw createError({
      statusCode: 400,
      message: fromError(validationResult.error).toString()
    })
  }

  const { remark = '', name, value } = validationResult.data

  try {
    // 创建用户
    const [newRole] = await db
      .insert(rolesTable)
      .values({
        name,
        value,
        remark
      })
      .$returningId()
    setResponseStatus(event, 201)
    return {
      message: '角色创建成功',
      data: newRole.id
    }
  } catch (error: any) {
    if ((error as QueryError).code === 'ER_DUP_ENTRY') {
      throw createError({
        statusCode: 409,
        message: '角色已存在'
      })
    }
    console.error('Create role error:', error)
    throw createError({
      statusCode: 500,
      message: '创建角色失败'
    })
  }
})
